package net.zisen.cloud.wallet.service;

import com.codingapi.txlcn.tc.annotation.LcnTransaction;
import net.zisen.cloud.base.msg.ResultMsg;
import net.zisen.cloud.wallet.model.Wallet;
import org.beetl.sql.core.SQLManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * @author tim/278002989@qq.com
 * @Classname WalletServiceImpl
 * @Description TODO
 * @Date 2019-05-17 19:15
 */
@Service
public class WalletServiceImpl implements WalletService {

    @Autowired
    private SQLManager sqlManager;

    /**
     * 扣除钱包金额
     *
     * @param uid
     * @param amount
     * @param num
     * @param description
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class, timeout = 60, isolation = Isolation.READ_COMMITTED)
    @LcnTransaction
    public ResultMsg deduct(Long uid, BigDecimal amount, String num, String description) {
        Wallet wallet = sqlManager.query(Wallet.class).andEq("uid", uid).single();
        if (wallet == null) {
            return ResultMsg.fail().resultMsg("未找到钱包信息");
        }
        if (wallet.getAmount().compareTo(amount) < 0) {
            return ResultMsg.fail().resultMsg("钱包金额不足");
        }
        wallet.setAmount(wallet.getAmount().subtract(amount));
        this.sqlManager.updateById(wallet);
        return ResultMsg.ok().data(wallet.getAmount());
    }

    /**
     * 查询钱包余额
     *
     * @param uid
     * @return
     */
    @Override
    @Transactional(readOnly = true)
    public ResultMsg<BigDecimal> checkWalletBalance(Long uid) {
        Wallet wallet = sqlManager.query(Wallet.class).andEq("uid", uid).single();
        if (wallet == null) {
            return ResultMsg.fail().resultMsg("未找到钱包信息");
        }
        return ResultMsg.ok().data(wallet.getAmount());
    }
}
